/*
 * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of either the GNU General Public License version 2
 * or the GNU Lesser General Public License version 2.1, both as
 * published by the Free Software Foundation.
 */

#include <stdio.h>
#include <string.h>
#include <avr/interrupt.h>

#include "new_w5300.h"

// W5300 controller instance
W5300Class W5300;

//#define TX_RX_MAX_BUF_SIZE 2048
//#define TX_BUF 0x1100
//#define RX_BUF (TX_BUF + TX_RX_MAX_BUF_SIZE)

//#define TXBUF_BASE 0x4000
//#define RXBUF_BASE 0x6000

uint8 W5300Class::tx_mem_conf[W5300Class::SOCKETS] = {8,8,8,8,8,8,8,8}; // for setting TMSR regsiter
uint8 W5300Class::rx_mem_conf[W5300Class::SOCKETS] = {8,8,8,8,8,8,8,8}; // for setting RMSR regsiter

void W5300Class::init(void)
{
  iinchip_init();
  ::sysinit(tx_mem_conf, rx_mem_conf);
}

uint32_t W5300Class::getTXFreeSize(SOCKET s)
{
  return readSn_TX_FSR(s);
}

uint32_t W5300Class::getRXReceivedSize(SOCKET s)
{
  return readSn_RX_RSR(s);
}

void W5300Class::send_data_processing(SOCKET s, const uint8_t *data, uint32_t len)
{
  // This is same as having no offset in a call to send_data_processing_offset
  wiz_write_buf(s, (uint8*)data, len);
}



void W5300Class::recv_data_processing(SOCKET s, uint8_t *data, uint32_t len)
{
  read_data(s, data, len);
}

void W5300Class::read_data(SOCKET s, uint8_t *data, uint32_t len)
{
  wiz_read_buf(s, data, len);
}


uint8_t W5300Class::write(uint16_t _addr, uint8_t _data)
{
  IINCHIP_WRITE(_addr, _data);
  return 1;
}

uint8_t W5300Class::read(uint16_t _addr)
{
  return IINCHIP_READ(_addr);
}

void W5300Class::execCmdSn(SOCKET s, SockCMD _cmd) {
  // Send command to socket
  writeSn_CR(s, _cmd);
  // Wait for command to complete
  while (readSn_CR(s))
    ;
}
